﻿using UnityEngine;
using System.Collections;

public class FuelBarrel : MonoBehaviour 
{
	public CSVReader m_csvReader;
	public string[,] m_grid;

	private Camera m_mainCamera;
	// Use this for initialization
	void Start () 
	{
		m_grid = m_csvReader.GetGrid();
		m_mainCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
		Respawn();
	}

	void Awake()
	{
		m_grid = m_csvReader.GetGrid();
		m_mainCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
		Respawn();
	}

	// Update is called once per frame
	void Update () 
	{

	}

	public void Respawn()
	{
		//Debug.Log("Fuel Barrel Respawn ");
		do
		{

			int x = Random.Range(1, 15 );
			int y = Random.Range(1, 10 );
			//Debug.Log("Spawn loc " + x + ","+y);
			if( m_grid[x, y] == "1" && m_csvReader.HasParsed() )
			{
				//Debug.Log("Spawning at " + x + ","+y);
				transform.position = new Vector3(x * 64 + (m_mainCamera.transform.position.x - m_mainCamera.pixelRect.width * 0.5f), 
				                                 Screen.height - ( y * 64) + (m_mainCamera.transform.position.y - m_mainCamera.pixelRect.height * 0.5f), 
				                                 0.0f);

				break;
			}
			else if ( !m_csvReader.HasParsed() )
			{
				break;
			}
			else
			{
				Debug.Log("Respawn, reattempt ");
				//break;
			}

		}while(true);
	}
	
}
